import { defineEventHandler, readBody } from 'h3'
import { getPool } from '../../util/mysql'
import { checkAdminKey } from './_utils'

function now() { return new Date() }

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  const body = await readBody(event).catch(() => ({}))
  const name = body.product_name || ''
  if (!name) {
    event.node.res.statusCode = 400
    return { status: 400, message: 'product_name required' }
  }

  try {
    const pool = await getPool()
    // lin_product.id is defined as bigint in the schema. Use a numeric id to avoid
    // "Data truncated for column 'id'" errors when inserting UUID strings.
    // Use current milliseconds timestamp as a numeric id. If you prefer a DB-side
    // auto-increment, consider altering the table to add AUTO_INCREMENT.
    const id = Date.now()
    const price = body.price || 0
    const is_sale = body.is_sale ? 1 : 0
    const quantity = body.quantity || 0
    const product_info = body.product_info || ''
    const image_base64 = body.image_base64 || null
    // Prevent extremely large payloads from attempting to insert into DB.
    if (image_base64 && typeof image_base64 === 'string' && image_base64.length > 16000000) {
      event.node.res.statusCode = 400
      return { status: 400, message: 'image_base64 too large; please upload a smaller image or store externally (limit ~16MB)' }
    }
    const detail = body.detail || ''
    const creator_id = 0
    const creation_time = now()

    await pool.execute(
      `INSERT INTO lin_product (id, product_name, price, is_sale, quantity, product_info, image_base64, detail, creator_id, creation_time, is_deleted)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)`,
      [id, name, price, is_sale, quantity, product_info, image_base64, detail, creator_id, creation_time]
    )

    return { ok: true, id }
  } catch (err: any) {
    event.node.res.statusCode = 500
    const res: any = { status: 500, message: String(err?.message || err) }
    if (process.env.NODE_ENV !== 'production') res.stack = err?.stack
    return res
  }
})
